// ++++++++++++++++++++++++++++++++++++++++
// 《Go 语言+Vue.js 实战派——基于 Gin 框架》源码
// ++++++++++++++++++++++++++++++++++++++++
// 作者公众号：源码大数据
// 自媒体账号（抖音、视频号、快手、B站、知乎）：廖显东-ShirDon
// 仓库地址：https://gitee.com/shirdonl/goGinVue.git
// 仓库地址：https://github.com/shirdonl/goGinVue.git
// 博客：https://www.shirdon.com
// 购买图书：https: //item.jd.com/14958064.html
// ++++++++++++++++++++++++++++++++++++++++

package main

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	router := gin.Default()

	store := cookie.NewStore([]byte("secret"))
	router.Use(sessions.Sessions("testSession", store))

	router.POST("/login", func(c *gin.Context) {
		// 检查用户名和密码
		validUser := true
		if validUser {
			session := sessions.Default(c)
			session.Set("userId", "88")
			session.Save()

			c.JSON(http.StatusOK, gin.H{"status": "ok"})
		} else {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
		}
	})

	router.Use(authMiddleware())

	router.GET("/protected", func(c *gin.Context) {
		userID, _ := c.Get("userId")
		c.JSON(http.StatusOK, gin.H{"userId": userID})
	})
}

func authMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		userID := session.Get("userId")
		if userID == nil {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		c.Set("userId", userID)
		c.Next()
	}
}
